package com.qiaoba.file.local.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import com.qiaoba.api.file.core.FileCore;
import com.qiaoba.api.file.entity.vo.FileUploadVO;
import com.qiaoba.api.file.util.FileUtil;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.common.base.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

/**
 * 本地 文件服务实现
 *
 * @author ailanyin
 * @date 2023-09-26 14:36:52
 */
@Service
@RequiredArgsConstructor
public class LocalFileServiceImpl implements FileCore {

    @Value("${file.ip}")
    private String ip;

    @Value("${file.uploadPath}")
    private String uploadPath;

    @Value("${server.port}")
    private String port;

    @Override
    public FileUploadVO upload(String bucketName, String filename, Long size, InputStream inputStream) {
        try {
            String path = DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + java.util.UUID.randomUUID().toString() + "." + FileUtil.getExtension(filename);
            String fileName = bucketName + "/" + path;
            // 新建文件
            File file = getAbsoluteFile(fileName);
            // 写入流
            cn.hutool.core.io.FileUtil.writeFromStream(inputStream, file, false);
            FileUploadVO vo = new FileUploadVO();
            vo.setFileName(filename);
            vo.setPath(path);
            vo.setUrl(getUrl(fileName));
            return vo;
        } finally {
            IoUtil.close(inputStream);
        }
    }

    @Override
    public void delete(String bucketName, String path) {
        String localPath = uploadPath + bucketName + "/" + path;
        if (cn.hutool.core.io.FileUtil.isDirectory(localPath)) {
            throw new ServiceException("删除路径异常, 请勿非法操作");
        }
        cn.hutool.core.io.FileUtil.del(localPath);
    }


    /**
     * 创建文件
     *
     * @param fileName 文件名
     * @return file
     */
    private File getAbsoluteFile(String fileName) {
        File desc = new File(uploadPath + "/" + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                boolean result = desc.getParentFile().mkdirs();
                if (!result) {
                    throw new ServiceException("上传文件-创建父目录失败");
                }
            }
        }
        return desc;
    }

    private String getUrl(String fileName) {
        // http://192.168.2.13:8080/resource/pic/2023/09/27/415554ee-9ee8-4822-9b5d-4924564d3f3a.txt
        return "http://" + ip + ":" + port + BaseConstant.RESOURCE_PREFIX + "/" + fileName;
    }

}
